package ee.siimkaspar.subjects.interceptor;

import java.util.Map;

import org.apache.log4j.Logger;

import com.opensymphony.xwork2.ActionInvocation;

import ee.siimkaspar.subjects.model.UserAccount;
import ee.siimkaspar.subjects.service.UserService;
import ee.siimkaspar.subjects.util.Const;

public class LoginInterceptor extends BaseInterceptor {
	
	private static final long serialVersionUID = 1L;
	private UserService uService;

	public LoginInterceptor(UserService uService) {
        this.uService = uService;
    }

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		Logger.getLogger(getClass()).debug("LOGIN INTERCEPTOR");
		Map<String, Object> session = invocation.getInvocationContext().getSession();
		boolean isUserLoggedIn = (session.get(Const.SESSION_USER) instanceof UserAccount);
        boolean userExists = false;
        if (isUserLoggedIn) {
        	UserAccount user = (UserAccount) session.get(Const.SESSION_USER);
        	userExists = uService.findObject(UserAccount.class, user.getId()) != null;
        	if (!userExists) {
                Logger.getLogger(LoginInterceptor.class).debug("User was logged in but no longer exists");
                addActionError(invocation, "User doesnt exist!");
                return USER_DOESNT_EXIST;
            } else {
            	Logger.getLogger(LoginInterceptor.class).debug("User exists and is fine");
            }
        	
        } else {
        	Logger.getLogger(LoginInterceptor.class).debug("User not logged in");
            addActionError(invocation, "User is not logged in!");
            return NOT_LOGGED_IN;
        }
		return invocation.invoke();
	}

}
